package com.lemon.cloud.datascope.sqlFilter;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.lemon.cloud.comm.constants.OAuth2Constant;
import com.lemon.cloud.comm.constants.enums.ApplicationEnum;
import com.lemon.cloud.comm.constants.enums.DataScopeTypeEnum;
import com.lemon.cloud.comm.po.RoleApplication;
import com.lemon.cloud.core.utils.WebUtils;
import com.lemon.cloud.datascope.annotation.DataColumn;
import com.lemon.cloud.datascope.service.DataScopeHelper;
import com.lemon.cloud.datascope.service.DataScopeService;
import com.lemon.cloud.security.model.SecurityUser;
import com.lemon.cloud.security.util.SecurityUtils;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.LongValue;
import net.sf.jsqlparser.expression.operators.conditional.AndExpression;
import net.sf.jsqlparser.expression.operators.relational.EqualsTo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 部门过滤
 *
 * @author HuangDS
 */
@Service
public class OrgScopeSqlFilter implements SqlFilter {

    @Autowired
    private DataScopeService dataScopeService;

    @Override
    public Expression calcScope(DataColumn dataColumns, Expression expression, SecurityUser user) {
        List<String> roleCode = SecurityUtils.getRoleCode();
        if (CollectionUtil.isEmpty(roleCode)) {
            //没有角色返回空数据
            return nullScopeExpression(expression);
        }
        String appId = WebUtils.getAppId(OAuth2Constant.APP_ID_HEAD);
        if (StrUtil.isEmpty(appId)){
            appId = ApplicationEnum.BASE_PLATFORM.getId().toString();
        }
        List<RoleApplication> roleApplicationList = dataScopeService.getDSList(roleCode,appId);
        if (CollectionUtil.isEmpty(roleApplicationList)) {
            return nullScopeExpression(expression);
        }
        Map<Integer, List<RoleApplication>> map = roleApplicationList.stream().collect(Collectors.groupingBy(RoleApplication::getScopeType));
        if (CollectionUtil.isNotEmpty(map.get(DataScopeTypeEnum.ALL.getType()))){
            //查询全部
            return expression;
        }else {
            HashSet<Long> dataList = Sets.newHashSet();

            List<RoleApplication> custom = map.get(DataScopeTypeEnum.CUSTOM.getType());
            if (CollectionUtil.isNotEmpty(custom)){
                custom.forEach(item->{
                    if (CollectionUtil.isNotEmpty(item.getOrgIdList())){
                        dataList.addAll(item.getOrgIdList());
                    }
                });
            }

            List<RoleApplication> ownChild = map.get(DataScopeTypeEnum.OWN_CHILD_LEVEL.getType());
            List<Long> orgIds = SecurityUtils.getUser().getOrgIds();
            if (CollectionUtil.isNotEmpty(ownChild)){
                dataList.addAll(dataScopeService.getDescendantList(orgIds));
            }
            List<RoleApplication> own = map.get(DataScopeTypeEnum.OWN_LEVEL.getType());
            if (CollectionUtil.isNotEmpty(own)){
                dataList.addAll(orgIds);
            }
            //存在全部就不用判断
            //否则做聚合
            if (CollectionUtil.isEmpty(dataList)){
                return nullScopeExpression(expression);
            }
            String tableAlias = dataColumns.alias();
            String columnName = dataColumns.name();
            Expression rightExpression = DataScopeHelper.getRightExpressionById(tableAlias, columnName, Lists.newArrayList(dataList));
            return new AndExpression(expression, rightExpression);
        }
    }


    private Expression nullScopeExpression(Expression expression){
        EqualsTo equalsTo = new EqualsTo(new LongValue(1),new LongValue(0));
        return new AndExpression(expression,equalsTo);
    }
}
